package com.inkrl.collect.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.inkrl.collect.mapper.CollectMapper;
import com.jt.common.pojo.Book;
import com.jt.common.pojo.Collect;
import com.jt.common.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CollectServiceImpl implements CollectService {
    @Autowired(required = false)
    private CollectMapper collectMapper;
    @Autowired
    private StringRedisTemplate template;
    private static final ObjectMapper mapper = new ObjectMapper();
    @Override
    public List<Book> queryCollect(String token) {
        List<Book>  list =null;
        if (template.hasKey(token)){
            list = collectMapper.selectByIsbn();
            return list;
        }
        return null;
    }

    @Override
    public int addCollect(String isbn,String token) {
        ValueOperations<String,String> opsForValue = template.opsForValue();
        if (template.hasKey(token)){
            try {
                String userJson = opsForValue.get(token);
                User user = mapper.readValue(userJson,User.class);
                String userId = user.getPhone();
                Collect collect = collectMapper.selectByIsbnAndUserid(isbn,userId);
                if (collect==null){
                    collectMapper.insertCollect(isbn,userId);
                    return 0200;
                }else {
                    collectMapper.deleteCollect(isbn,userId);
                    return 0201;
                }
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
        return 1406;
    }
}
